package com.mall.web.control.weishang;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mall.biz.ImageUploadBizImpl;
import com.mall.biz.item.MallItemBizImpl;
import com.mall.biz.user.record.CollectionBizImpl;
import com.mall.client.item.MallItemPriceService;
import com.mall.client.item.MallItemService;
import com.mall.client.mall.MallService;
import com.mall.client.mallCategory.MallCategoryService;
import com.mall.client.user.UserLevelService;
import com.mall.common.util.PageUtil;
import com.mall.constant.UserConstant;
import com.mall.enums.CollectionEnum;
import com.mall.pojo.Mall;
import com.mall.pojo.MallCategory;
import com.mall.pojo.MallCategoryExample;
import com.mall.pojo.MallCategoryExample.Criteria;
import com.mall.pojo.MallItem;
import com.mall.pojo.MallItemPrice;
import com.mall.pojo.User;
import com.mall.pojo.UserLevel;
import com.mall.query.MallItemQuery;
import com.mall.query.Page;
import com.mall.vo.common.CategoryVO;
import com.mall.vo.weishang.MallItemPriceVO;
import com.mall.web.annotation.AdminSecurity;
import com.mall.web.annotation.WeishangSecurity;
import com.mall.web.util.HttpUtil;
import com.mall.web.util.MoneyUtil;
import com.mall.web.util.WebUtil;
import com.mall.web.vo.ResponseEntity;

@Controller
@RequestMapping("/weishang/item/")
public class WeishangItemController {
	private static final Logger log = LoggerFactory.getLogger(WeishangItemController.class);
	@Autowired
	private MallCategoryService mallCategoryService;
	@Autowired
	private MallService mallService;
	@Autowired
	private MallItemService mallItemService;
	@Autowired
	private ImageUploadBizImpl imageUploadBizImpl;
	@Autowired
	private MallItemPriceService mallItemPriceService;
	@Autowired
	private UserLevelService userLevelService;
	@Autowired
	private CollectionBizImpl collectionBizImpl;
	@Autowired
	private MallItemBizImpl mallItemBizImpl;
	
	
	
	// 图片保存的文件夹名字
	private final String folder = "weishang";
	
	/**
	 * 商品列表页
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("itemList")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String itemList(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		itemListModelMap(request,response,modelMap);
		return "weishang/item/itemList";
	}
	
	/**
	 * 商品列表加载更多
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("itemListMore")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String itemListMore(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		itemListModelMap(request,response,modelMap);
		return "weishang/item/itemListMore";
	}
	
	/**
	 * 供应商获得商品列表的map
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	public ModelMap itemListModelMap(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		User user = WebUtil.getCurrentUser(request);
		Mall mall = this.mallService.getMallByUserIdAndOnlyKey(user.getId(), onlyKey);
		if(mall == null){
			return null;
		}
		Long categoryId = HttpUtil.getLongValueFromRequest(request, "categoryId");
		Integer status = HttpUtil.getIntegerValueFromRequest(request, "status");//1待上线（下架） 0上线（上架）
		Integer stock = HttpUtil.getIntegerValueFromRequest(request, "stock");//库存    0：已售罄
		
		//获取供应商的类目列表
		MallCategoryExample mallCategoryExample = new MallCategoryExample();
		com.mall.pojo.MallCategoryExample.Criteria categoryCriteria = mallCategoryExample.createCriteria();
		categoryCriteria.andCommOnlyKeyEqualTo(onlyKey);
		categoryCriteria.andParentIdEqualTo(0);
		categoryCriteria.andStatusNotEqualTo(-1);
		List<CategoryVO> categoryVOList = new ArrayList<CategoryVO>();
		List<MallCategory> firstCategoryList = this.mallCategoryService.getMallCategoryList(mallCategoryExample);
		if(firstCategoryList != null && firstCategoryList.size() > 0){
			for(MallCategory firstCategory : firstCategoryList){
				CategoryVO categoryVO = new CategoryVO();
				List<MallCategory> secCategoryList = this.mallCategoryService.getSecMallCategoryListByParentMallCategoryId(firstCategory.getId());
				categoryVO.setFirstCategory(firstCategory);
				categoryVO.setSecCategoryList(secCategoryList);
				categoryVOList.add(categoryVO);
			}
		}
		
		
		// 设置分页
		Page page = new Page();
		int pageNo = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageNo", 1);
		int pageSize = HttpUtil.getIntegerValueHasDefaultFromRequest(request, "pageSize", PageUtil.PAGE_SIZE_APP);
		page.setPageByPageNoAndPageSize(pageNo, pageSize);
		
		//获取满足条件的所有商品
		MallItemQuery mallItemQuery = new MallItemQuery();
		mallItemQuery.setPage(page);
		mallItemQuery.setItemCategoryId(categoryId);
		mallItemQuery.setOnlyKey(onlyKey);
		mallItemQuery.setStatus(status);
		mallItemQuery.setStock(stock);
		mallItemQuery.setMallId(mall.getId());
		List<MallItem> mallItemList = this.mallItemBizImpl.getMallItemByQuery(mallItemQuery);
		
		modelMap.put("categoryVOList", categoryVOList);
		modelMap.put("mallItemList", mallItemList);
		modelMap.put("user", user);
		return modelMap;
	}
	
	
	
	/**
	 * 点击一级类目显示二级类目
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("secMallCategoryJson")
	public ResponseEntity<List<MallCategory>> secMallCategoryJson(HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		Integer mallCategoryId = HttpUtil.getIntegerValueFromRequest(request, "mallCategoryId");
		ResponseEntity<List<MallCategory>> responseEntity = new ResponseEntity<>();
		if (mallCategoryId == null || mallCategoryId <= 0) {
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("error");
			return responseEntity;
		}
		MallCategoryExample exampleSec = new MallCategoryExample();
		Criteria criterias = exampleSec.createCriteria();
		criterias.andStatusEqualTo(0);
		criterias.andParentIdEqualTo(mallCategoryId);
		List<MallCategory> mallSecCategoryList = this.mallCategoryService.getMallCategoryList(exampleSec);
		responseEntity.setCode("200");
		responseEntity.setData(mallSecCategoryList);
		responseEntity.setMessage("succ");
		return responseEntity;
	}
	
	
	/**
	 * 增加或修改商品跳转页
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("addOrModifyItem")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String addOrModifyItem(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Long mallItemId = HttpUtil.getLongValueFromRequest(request, "mallItemId");
		MallItem mallItem = this.mallItemService.getMallItemById(mallItemId);
		List<UserLevel> userLevelList = this.userLevelService.getUserLevelListByKey(onlyKey);//供应商设置的分销商级别
		List<MallCategory> firstCategoryList = this.mallCategoryService.getFirstMallCategoryListByKey(onlyKey);//所有一级类目
		
		if(mallItem != null){			
			//一二级类目
			MallCategory secCategory = this.mallCategoryService.getMallCategoryById(mallItem.getItemCategoryId().intValue());
			MallCategory firstCategory = this.mallCategoryService.getMallCategoryById(secCategory.getParentId().intValue());
			
			//一级类目下的二级类目结合
			List<MallCategory> secCategoryList = this.mallCategoryService.getSecMallCategoryListByParentMallCategoryId(secCategory.getParentId());
			
			if(userLevelList != null && userLevelList.size() > 0){
				for(UserLevel userLevel : userLevelList){
					//商品各级别价格
					MallItemPrice mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(Long.valueOf(userLevel.getLevel()), onlyKey, mallItemId,null);
					if(mallItemPrice != null){
						String levelPrice = new BigDecimal(mallItemPrice.getDiscoutPrice()).divide(new BigDecimal(100)).doubleValue()+","+mallItemPrice.getLimitNum()+","+mallItemPrice.getStatus();
						userLevel.setAttribute(levelPrice);
					}
				}
			}
			modelMap.put("secCategoryList", secCategoryList);
			modelMap.put("firstCategory", firstCategory);
			modelMap.put("secCategory", secCategory);
		}
		modelMap.put("firstCategoryList", firstCategoryList);
		modelMap.put("userLevelList", userLevelList);
		modelMap.put("mallItem", mallItem);
		return "weishang/item/addOrModifyItem";
	}
	
	/**
	 * 提交商品信息
	 * @param request
	 * @param response
	 * @param modelMap
	 * @param itemPics
	 * @return
	 */
	@RequestMapping("addOrModifyItemAction")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@Transactional
	public String addOrModifyItemAction(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap,
			@RequestParam("mainPics") MultipartFile[] mainPics,@RequestParam("otherPics") MultipartFile[] otherPics,MallItem mallItem){
		
		Integer onlyKey =HttpUtil.getCommkeyId(request, response);
		
		User user = WebUtil.getCurrentUser(request);
		Mall mall = this.mallService.getMallByUserIdAndOnlyKey(user.getId(), onlyKey);
		String stringPrice = HttpUtil.getStringValueFromRequest(request, "stringPrice");
		Long itemCategoryId = HttpUtil.getLongValueFromRequest(request, "mallcategoryid");
		mallItem.setItemCategoryId(itemCategoryId);
		Long mallItemId = HttpUtil.getLongValueFromRequest(request, "itemId");
		
		//item图片上传
		String mainPicFileNameAll = getUploadPicFullName(mainPics,request);
		String otherPicFileNameAll = getUploadPicFullName(otherPics,request);
		mallItem.setMallId(mall.getId());
		mallItem.setType(0);
		mallItem.setCommOnlyKey(onlyKey);
		mallItem.setPrice(new BigDecimal(stringPrice).multiply(new BigDecimal(100)).longValue());
		if(mallItemId == null || mallItemId <= 0){
			mallItem.setMainPic(mainPicFileNameAll);
			mallItem.setOtherPic(otherPicFileNameAll);
			mallItem.setSaleNo(0l);
			this.mallItemService.insertMallItem(mallItem);
	
		}else{
			MallItem mallItemed = this.mallItemService.getMallItemById(mallItemId);
			String mainPicDel = HttpUtil.getStringValueFromRequest(request, "mainPicDel");
			String otherPicDel = HttpUtil.getStringValueFromRequest(request, "otherPicDel");
			String endMainPicFileName = getModifyPicFileName(mainPicDel,mallItemed.getMainPic(),mainPicFileNameAll);
			String endotherPicFileName = getModifyPicFileName(otherPicDel,mallItemed.getOtherPic(),otherPicFileNameAll);
			mallItem.setMainPic(endMainPicFileName);
			mallItem.setOtherPic(endotherPicFileName);
			mallItem.setSaleNo(mallItemed.getSaleNo());
			mallItem.setGmtCreate(mallItemed.getGmtCreate());
			mallItem.setId(mallItemId);
			this.mallItemService.modifyMallItemByPrimarykey(mallItem);
		}

		//设置各分销商的价格
		Integer fenxiaoNum = HttpUtil.getIntegerValueFromRequest(request, "fenxiaoNum");
		
		List<MallItemPrice> mallItemPriceList = new ArrayList<>();
		if(fenxiaoNum != null && fenxiaoNum > 0){
			for(int i=1;i <= fenxiaoNum;i++){
				String fenxiaoPriceArr = HttpUtil.getStringValueFromRequest(request, "fenxiao"+i);
				String[] fenxiaoPrice = fenxiaoPriceArr.split(",");
				Long discountPrice =MoneyUtil.getPriceByString(fenxiaoPrice[0]);
				Integer limitNum = Integer.parseInt(fenxiaoPrice[1]);
				Integer fenxiaoStatus = Integer.parseInt(fenxiaoPrice[2]);//0允许订货  1不允许订货
				Long level = new Long(i);
				MallItemPrice mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(level, onlyKey,mallItem.getId(),null);
				if(mallItemPrice == null){
					MallItemPrice mallItemPriceNew = new MallItemPrice();
					mallItemPriceNew.setCreateUserId(user.getId());
					mallItemPriceNew.setDiscoutPrice(discountPrice);
					mallItemPriceNew.setLevel(level);
					mallItemPriceNew.setCommOnlyKey(onlyKey);
					mallItemPriceNew.setLimitNum(limitNum);
					mallItemPriceNew.setMallItemId(mallItem.getId());
					mallItemPriceNew.setPrice(mallItem.getPrice());
					mallItemPriceNew.setStatus(fenxiaoStatus);
					mallItemPriceNew.setGmtCreate(new Date());
					mallItemPriceNew.setGmtModify(new Date());
					mallItemPriceNew.setType(0);
					mallItemPriceNew.setAttribute(null);
					mallItemPriceList.add(mallItemPriceNew);
				}else{
					mallItemPrice.setDiscoutPrice(discountPrice);
					mallItemPrice.setLevel(level);
					mallItemPrice.setLimitNum(limitNum);
					mallItemPrice.setPrice(mallItem.getPrice());
					mallItemPrice.setStatus(fenxiaoStatus);
					mallItemPriceList.add(mallItemPrice);
				}
			}
		}
		this.mallItemPriceService.replaceMallItemPriceList(mallItemPriceList);
		return "redirect:/weishang/item/itemDetail.htm?mallItemId="+mallItem.getId();
		
	}
	
	
	//图片上传
	private String getUploadPicFullName(MultipartFile[] pic ,HttpServletRequest request){
		String picFileNameAll = "";
		if(pic == null || pic.length <= 0){
			return picFileNameAll;
		}
		if (pic != null && pic.length > 0) {
			int picsLength = pic.length;
			
			for (int i = 0; i < picsLength; i++) {//这个是for循环
				if(pic[i] != null && !pic[i].getOriginalFilename().equals("")){//编辑时已有的图片会传"",添加图片的input也会带一个""
					String itemPicUploadFileName = imageUploadBizImpl.uploadImage(pic[i], folder, request);
					if (picFileNameAll.equals("")) {
						picFileNameAll = itemPicUploadFileName;
					} else {
						picFileNameAll = picFileNameAll + "," + itemPicUploadFileName;
					}
				}
			}
		}
		return picFileNameAll;
	}
	
	private String getModifyPicFileName(String delPic,String oldPicFileName,String uploadPicFileNameAll){
		//原数 路径据库
		String[] oldPic = oldPicFileName.split(",");
		//原主图路径减去删除的图片路径
		if(delPic != null && !delPic.equals("")){
			String[] picDelNum = delPic.split(",");
			//用户删除时会不按顺序删除，因此需要事先排序，然后转成集合进行删除对应图片
			Arrays.sort(picDelNum);
			List<String> picList = Arrays.asList(oldPic);
			List<String> allPicList = new ArrayList<String>(picList);
			//必须从后往前删，不然下标会弄错
			for(int i = picDelNum.length-1;i >= 0;i--){
				allPicList.remove(Integer.parseInt(picDelNum[i]));
			}
			//去掉删除的图片后留下的图片路径
			String leavePic = StringUtils.join(allPicList.toArray(), ","); 
			//存入修改后的图片路径
			if(uploadPicFileNameAll.equals("")){
				return leavePic;
			}else if(!uploadPicFileNameAll.equals("") && !leavePic.equals("")){
				return uploadPicFileNameAll+","+leavePic;
			}else if(!uploadPicFileNameAll.equals("") && leavePic.equals("")){
				return uploadPicFileNameAll;
			}
		}else{
			if(uploadPicFileNameAll == null || uploadPicFileNameAll.equals("")){
				return oldPicFileName;
			}else{
				return oldPicFileName+","+uploadPicFileNameAll;
			}
			
		}
		return null;
	}
	
	/**
	 * 供应商商品详情页
	 * @param request  
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("itemDetail")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	public String itemDetail(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		Long mallItemId = HttpUtil.getLongValueFromRequest(request, "mallItemId");
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		MallItem mallItem = this.mallItemService.getMallItemById(mallItemId);
		if(mallItem == null){
			return null;
		}
		List<MallItemPrice> mallItemPriceList = this.mallItemPriceService.getMallItemPriceByItemIdAndKey(onlyKey,mallItemId,0);	
		List<MallItemPriceVO> mallItemPriceVOList = new ArrayList<MallItemPriceVO>();
		if(mallItemPriceList != null && mallItemPriceList.size() > 0){
			for(MallItemPrice mallItemPrice : mallItemPriceList){
				MallItemPriceVO mallItemPriceVO = new MallItemPriceVO();
				mallItemPriceVO.setMallItemPrice(mallItemPrice);
				mallItemPriceVO.setLevelName(this.userLevelService.getUserLevelByLevelAndKey(mallItemPrice.getLevel().intValue(), onlyKey).getLevelName());
				mallItemPriceVOList.add(mallItemPriceVO);
			}
		}
		modelMap.put("mallItem", mallItem);
		modelMap.put("mallItemPriceVOList", mallItemPriceVOList);
		return "weishang/item/itemDetail";
	}
	
	/**
	 * 分销商商品详情页
	 * @param request  
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("distributorItemDetail")
	@WeishangSecurity
	public String distributorItemDetail(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		User user = WebUtil.getCurrentUser(request);
		Integer onlyKey = HttpUtil.getCommkeyId(request, response);
		Long mallItemId = HttpUtil.getLongValueFromRequest(request, "mallItemId");
		
		MallItem mallItem = this.mallItemService.getMallItemById(mallItemId);
		if(mallItem == null){
			return null;
		}
		//该用户级别对应的价格
		MallItemPrice mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(user.getLevel().longValue(), onlyKey, mallItemId, 0);
		if(mallItemPrice == null){//假如该级别的商品价格供应商没有设置，则默认为一级分销商的价格
			mallItemPrice = this.mallItemPriceService.getMallItemPriceByLevelAndKey(1l, onlyKey, mallItemId, 0);
		}
		//判断该商品是否已经被用户假如购物车 0收藏  
		int isCollection = this.collectionBizImpl.isCollection(onlyKey, mallItemId, user, CollectionEnum.WEISHANG.getCode());
		modelMap.put("mallItem", mallItem);
		modelMap.put("mallItemPrice", mallItemPrice);
		modelMap.put("isCollection", isCollection);
		return "weishang/item/distributorItemDetail";
	}
	 
	/**
	 * 修改商品状态（上架‘下架'删除）
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping("modifyItemStatus")
	@AdminSecurity(userType = UserConstant.TYPE_MANAGE)
	@ResponseBody
	public ResponseEntity<String> modifyItemStatus(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		ResponseEntity<String> responseEntity = new ResponseEntity<>();
		Integer status = HttpUtil.getIntegerValueFromRequest(request, "status");//1:待上线     0：已经上线    -1：已下线   -8：删除
		Long mallItemId = HttpUtil.getLongValueFromRequest(request, "mallItemId");
		MallItem mallItem = this.mallItemService.getMallItemById(mallItemId);
		
		if(mallItem == null){
			log.error("mallitem not exist");
			responseEntity.setCode("-300");
			responseEntity.setData(null);
			responseEntity.setMessage("商品不存在");
			return responseEntity;
		}
		mallItem.setStatus(status);
		int isModify = this.mallItemService.modifyMallItemByPrimarykey(mallItem);
		if(isModify <= 0){
			log.error("modify error");
			responseEntity.setCode("-200");
			responseEntity.setData(null);
			responseEntity.setMessage("修改失败");
			return responseEntity;
		}
		responseEntity.setCode("200");
		responseEntity.setData(null);
		responseEntity.setMessage("修改成功");
		return responseEntity;
	}
	
	public static void main(String[] args) {
		String[] aa = "3,2,6,4,1".split(",");
		System.out.println(aa[0]);
		Arrays.sort(aa);
		System.out.println(aa[0]);
	}
}
